<template>
  <view class="home">
    <scroll-view
      scroll-x
      class="categories"
      :scroll-left="scrollLeft"
      scroll-with-animation
    >
      <view
        v-for="(category, index) in categories"
        :key="index"
        class="category"
        :class="{ highlighted: selectedIndex === index }"
        @click="selectCategory(index)"
      >
        {{ category.name }}</view
      >
    </scroll-view>
    <view class="topics">
      <topic v-for="topic in topics" :topic="topic" :key="topic.id"></topic>
    </view>
  </view>
</template>
<script>
import { fetchData, selectFromQuery } from "../../utils";
export default {
  data() {
    return {
      categories: [],
      selectedIndex: 0,
      scrollLeft: 0,
      currentPage: 1,
      pageSize: 10,
      topics: [],
      totalPages: 0,
      isLoading: false,
    };
  },
  async onLoad() {
    try {
      await this.fetchCategories();
      await this.fetchTopics();
    } catch (error) {
      console.log(error);
      uni.showToast({
        title: "获取数据失败",
        icon: "error",
        duration: 2000,
      });
    }
  },
  onReachBottom() {
    if (this.currentPage <= this.totalPages && !this.isLoading) {
      this.fetchTopics();
    } else {
      uni.showToast({
        title: "没有更多数据了",
        icon: "none",
        duration: 2000,
      });
    }
  },
  async onPullDownRefresh() {
    try {
      await this.refreshTopics();
    } catch (error) {
      uni.showToast({
        title: "刷新失败",
        icon: "error",
        duration: 2000,
      });
    } finally {
      uni.stopPullDownRefresh();
    }
  },
  methods: {
    async refreshTopics() {
      this.currentPage = 1;
      this.topics = [];
      await this.fetchTopics();
    },
    async fetchCategories() {
      this.categories = await fetchData({
        url: "/categories",
        method: "GET",
      });
    },
    async fetchTopics() {
      if (this.categories.length <= 0) return;
      const category_id = this.categories[this.selectedIndex].id;
      this.isLoading = true;
      uni.showLoading({
        title: "加载中...",
      });
      try {
        const response = await fetchData({
          url: `/topics?category_id=${category_id}&currentPage=${this.currentPage}&pageSize=${this.pageSize}`,
          method: "GET",
        });
        this.topics = this.topics.concat(response.list);
        this.totalPages = response.totalPages;
        this.currentPage++;
      } catch (error) {
        console.log(error);
      } finally {
        this.isLoading = false;
        uni.hideLoading();
      }
    },
    selectCategory(index) {
      if (index === this.selectedIndex) return;
      this.selectedIndex = index;
      const query = uni.createSelectorQuery().in(this);
      const scrollOffset = selectFromQuery(
        query,
        ".categories",
        "scrollOffset"
      );
      const elementRect = selectFromQuery(
        query,
        `.category:nth-child(${index + 1})`,
        "boundingClientRect"
      );
      Promise.all([scrollOffset, elementRect]).then(
        ([scrollOffset, elementRect]) => {
          this.scrollLeft =
            elementRect.left +
            scrollOffset.scrollLeft -
            uni.getSystemInfoSync().windowWidth / 2 +
            elementRect.width / 2;
          this.refreshTopics();
        }
      );
    },
  },
};
</script>
<style lang="scss" scoped>
.home {
  .categories {
    position: fixed;
    left: 0;
    top: var(--window-top);
    z-index: 100;
    white-space: nowrap;
    width: 100%;
    height: 100rpx;
    overflow-x: auto;
    overflow-y: hidden;
    background-color: #f5f5f5;
    /deep/ ::-webkit-scrollbar-horizontal {
      display: none;
    }
    .category {
      display: inline-block;
      height: 100%;
      padding: 0 20rpx;
      line-height: 100rpx;
      text-align: center;
      border: 1px solid #c5c5c5;
      box-sizing: border-box;
      &.highlighted {
        color: #1baeae;
        border: 1px dashed #1baeae;
      }
    }
  }
  .topics {
    padding-top: 100rpx;
  }
}
</style>
